<?php
/**
 * Created by PhpStorm.
 * User: jinqiang
 * Date: 2019/2/4
 * Time: 11:52
 */

namespace App\Http\Services\System;

use App\Http\Models\Mysql\NnyyRoleTable;
use App\Http\Models\Mysql\NnyyUserTable;
use Illuminate\Database\Eloquent\Model;

class UserService
{
    public function search($param)
    {
        //$field = ['name','phone','effect_time','role'];
        $conn = (new NnyyUserTable());
        //$conn = $conn->fromJson()
        if(!empty($param['name'])){
            $conn = $conn->where('name', 'like', $param['name']."%");
        }
        if(!empty($param['role'])){
            $conn = $conn->where('role', $param['role']);
        }
        if($param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        $res = $conn->orderBy('create_time', 'DESC')->paginate((Int)$param['limit'])->toArray();
        $roles = array_unique(array_column($res['data'], 'role'));
        $roleList = (new NnyyRoleTable())->whereIn('type', $roles)->get(['type', 'label'])->toArray();
        return ['data' => $res['data'], 'roles' => array_column($roleList, 'label', 'type'), 'total' => $res['total']];
    }

    public function setUser($id, $data)
    {
        try{
            return (new NnyyUserTable())->updateData($id, $data);
        }catch (\Exception $e){
            return ['code' => -1, 'msg' => "操作失败, 请修改内容重新设置"];
        }
    }

    public function resetPassword($param)
    {
        $user = (new NnyyUserTable())->where('name', $param['name'])->first(['password'])->toArray();
        if(!password_verify($param['password_old'], $user['password'])){
            return ['code' => -1, 'msg' => '提示：旧密码填写错误'];
        }
        $data = ['password' => bcrypt($param['password'])];
        return (new NnyyUserTable())->updateData($param['name'], $data);
    }

    public function updatePassword($param)
    {
        $data = ['password' => bcrypt($param['password'])];
        return (new NnyyUserTable())->updateDataByPhone($param['phone'], $data);
    }
}
